/**
 * hkx .
 *
 *
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.app.controller;


import io.renren.common.exception.RRException;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.app.annotation.Login;
import io.renren.modules.app.annotation.LoginUser;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.app.form.LoginForm;
import io.renren.modules.app.service.UserService;
import io.renren.modules.app.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * APP登录授权
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/app")
@Api("APP登录接口")
public class AppLoginController {
    @Autowired(required = false)
    private UserService userService;
    @Autowired(required = false)
    private JwtUtils jwtUtils;

    /**
     * 登录
     */
    @PostMapping("login")
    @ApiOperation("登录")
    public R login(@RequestBody LoginForm form){
        //表单校验
        ValidatorUtils.validateEntity(form);

        //用户登录
        UserEntity userEntity = userService.login(form);

        //生成token
        String token = jwtUtils.generateToken(userEntity);

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("expire", jwtUtils.getExpire());

        return R.ok(map);
    }

    @Login
    @PostMapping("user/lock")
    @ApiOperation("锁定用户")
    public R lockUser(@LoginUser UserEntity user){
        return R.ok(userService.updateById(new UserEntity().setUserId((long)user.getUserId()).setStatus(2)));
    }

    @Login
    @PostMapping("user/changePassword")
    @ApiOperation("修改用户密码")
    public R changeUserPassword(@LoginUser UserEntity user,@RequestBody UserDto userDto){
        //密码错误
        if(!user.getPassword().equals(DigestUtils.sha256Hex(userDto.getOldPassword()))){
            throw new RRException("旧密码错误");
        }
        user.setPassword(DigestUtils.sha256Hex(userDto.getNewPassword()));
        return R.ok(userService.saveOrUpdate(user));
    }

    @Data
    public static class UserDto{
        private String oldPassword;
        private String newPassword;
    }

}
